//
//  BoxTableViewController.m
//  myhuibao
//
//  Created by li jun on 13-3-8.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "BoxPhotoViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "BoxPhotoCell.h"
#import "OMGToast.h"
#import "config.h"
@interface BoxPhotoViewController ()

@end

@implementation BoxPhotoViewController
@synthesize mainTable;
@synthesize photoArray;
@synthesize delegatePassValue;
@synthesize selectedIds;
@synthesize req;
@synthesize reqBoxType;
@synthesize reqCapacity;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
   
//    [self getSearchResult];
//    [self getBoxType];
//    [self getCapacity];
}
-(void)viewDidAppear:(BOOL)animated
{
    wqTable = mainTable;
    tableDataArray = [photoArray copy];
    delegate=self;
    [mainTable reloadData];
    [Config setExtraCellLineHidden:mainTable ];
    _lbTitle.text = _mainTitle;
}
- (void)viewDidUnload
{
    [self setMainTable:nil];
    [self setLbBoxType:nil];
    [self setLbCapacity:nil];
    [self setLbTitle:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

/*
- (void) getSearchResult{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_boxList];
    req=[ASIFormDataRequest requestWithURL:url];
    [req setPostValue:[NSString stringWithFormat:@"%d",_merchantId] forKey:@"merchantID"];
    [req setPostValue:[NSString stringWithFormat:@"%@",_diningDate] forKey:@"diningDate"];
    [req setPostValue:[NSString stringWithFormat:@"%d",_diningTime] forKey:@"diningTime"];
    if(boxType !=0)
        [req setPostValue:[NSString stringWithFormat:@"%d",boxType] forKey:@"boxType"];
    if(capacityId !=0)
        [req setPostValue:[NSString stringWithFormat:@"%d",capacityId] forKey:@"capacityId"];
    [req setShouldAttemptPersistentConnection:NO];
    [req setDidFinishSelector:@selector(finishReq:)];
    isReqFinished = false;
    [req setDelegate: self];
    [req startAsynchronous];
}
//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)finishReq:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    isReqFinished = true;
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    
    tableDataArray = [dic valueForKey:@"data"];
    NSArray *ss = [selectedIds componentsSeparatedByString:@","];
    NSLog(@"%@",tableDataArray);

    for(int i=0;i<tableDataArray.count;i++)
    {
        NSMutableDictionary *item = [tableDataArray objectAtIndex:i];
        bool selected = [self isArray:ss contain:[NSString stringWithFormat:@"%d",[[item valueForKey:@"BOX_ID"] intValue] ]];
        if (selected)
            [item setValue:@"YES" forKey:@"checked"];
        else
            [item setValue:@"NO" forKey:@"checked"];
    }
    

    [mainTable reloadData];
    // Use when fetching binary data
    //    NSData *responseData = [request responseData];
}
- (void) getBoxType{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_boxType];
    reqBoxType = [ASIHTTPRequest requestWithURL:url];
    [reqBoxType setDidFinishSelector:@selector(finishBoxType:)];
    isBoxTypeFinished = false;
    [reqBoxType setShouldAttemptPersistentConnection:NO];
    [reqBoxType setDelegate: self];
    [reqBoxType startAsynchronous];
    
}
- (void) getCapacity{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_boxCapacity];
    reqCapacity = [ASIHTTPRequest requestWithURL:url];
    [reqCapacity setDidFinishSelector:@selector(finishCapacity:)];
    isCapacityFinished = false;
    [reqCapacity setShouldAttemptPersistentConnection:NO];
    [reqCapacity setDelegate: self];
    [reqCapacity startAsynchronous];
}
- (void)finishCapacity:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayCapacity = [dic valueForKey:@"data"];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"boxCapacityID",@"不限",@"boxCaptcityDesc",nil];
    [arrayCapacity insertObject: dict atIndex:0];
    isCapacityFinished = true;
}
- (void)finishBoxType:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayBoxType = [dic valueForKey:@"data"];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"0",@"boxTypeID",@"不限",@"boxTypeDesc",nil];
    [arrayBoxType insertObject: dict atIndex:0];
    isBoxTypeFinished = true;
}
- (bool)isArray:(NSArray *)a contain:(NSString*)s
{    
    for(NSString *ss in a)
    {
        if ([s isEqualToString:ss]) {
            return true;
        }
    }
    return false;
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    isReqFinished = true;
    isBoxTypeFinished = true;
    isCapacityFinished = true;
}

*/
// 列表设置
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 240;
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"BoxPhotoCellIdentifier";
    
    BoxPhotoCell *cell = (BoxPhotoCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
           if (cell == nil) {
    NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"BoxPhotoCell" owner:nil options:nil];
    cell = [array objectAtIndex:0];
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
            }
    
    NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
    //        显示图片
//    NSString * imageStr = [item valueForKey:@"IMAGE_PATH"];
    NSString * imageStr = [item valueForKey:@"image"];
    NSString *imageName =@"";
    if (![imageStr isEqual:[NSNull null] ]) {
        NSArray *array = [imageStr componentsSeparatedByString:@"/"];
        imageName = [array lastObject];
    }
    NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
    if (image) {
        cell.imageView.image = image;
    }
    else
    {
//        cell.imageView.image = [UIImage imageNamed:@"placeholder.png"];
        //placeholder为在未加载完成加载图片时显示的默认图片
    }
    //NSLog(@"%@",item);

    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   	
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
    //其他cell的事件
    
}
-(void)cellImageDidLoad:(NSIndexPath *)indexPath image:(UIImage *)image
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UITableViewCell *cell = [wqTable cellForRowAtIndexPath:indexPath];
        if(image)
        {
            cell.imageView.image = image;
        }
    });
    
    
}
- (IBAction)doBack:(id)sender {
//    if (!isReqFinished){
//        [req clearDelegatesAndCancel];
//        [req cancel];
//    }if (!isCapacityFinished){
//        [reqCapacity clearDelegatesAndCancel];
//        [req cancel];
//    }if (!isBoxTypeFinished){
//        [reqBoxType clearDelegatesAndCancel];
//        [reqBoxType cancel];
//    }
    [self.navigationController popViewControllerAnimated:YES];
//    [self dismissModalViewControllerAnimated:YES];
}
/*
- (IBAction)doSave:(id)sender {
    NSString *ids=@"";
    NSString *names=@"";
    for(int i=0;i<tableDataArray.count;i++)
    {
        NSMutableDictionary *item = [tableDataArray objectAtIndex:i];
        BOOL checked = [[item valueForKey:@"checked"] boolValue];
        if(checked)
        {
            ids = [ids stringByAppendingFormat:@"%@,",[item valueForKey:@"BOX_ID"]];
            names = [names stringByAppendingFormat:@"%@,",[item valueForKey:@"BOX_NAME"]];
        }
    }
//    if([ids isEqualToString:@""]==NO){
//        NSLog(@"%@", names);
        [delegatePassValue passBoxNames:names withIds:ids];
        [self.navigationController popViewControllerAnimated:YES];

//    }else{
//        [OMGToast showWithText:@"请选择包厢后点击完成。" bottomOffset:100];
//        [self.navigationController popViewControllerAnimated:YES];

//    }
}

- (IBAction)showBoxType:(id)sender {
    selectIndex = 5;
    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择包厢类型" options:arrayBoxType];
    lplv.name = @"boxTypeDesc";
    lplv.selectedIndex = _selectedIndex3;
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];
    [lplv release];
}

- (IBAction)showCapacity:(id)sender {
    selectIndex = 6;
    LeveyPopListView *lplv = [[LeveyPopListView alloc] initWithTitle:@"请选择包厢大小" options:arrayCapacity];
    lplv.name = @"boxCaptcityDesc";
    lplv.selectedIndex = _selectedIndex2;
    lplv.delegate = self;
    [lplv showInView:self.view animated:YES];
    [lplv release];
}
#pragma mark - LeveyPopListView delegates
- (void)leveyPopListView:(LeveyPopListView *)popListView didSelectedIndex:(NSInteger)anIndex options:(NSArray *)_options didSelectedTypeIndex:(NSInteger)anTypeIndex
{
    switch (selectIndex) {
       
        case 5:{
            _selectedIndex3 = anIndex;
            
            _lbBoxType.text = [NSString stringWithFormat:@"%@",[[arrayBoxType objectAtIndex:anIndex] objectForKey:@"boxTypeDesc"]];
            boxType= [[[arrayBoxType objectAtIndex:anIndex] objectForKey:@"boxTypeID"] intValue];
            break;}
        case 6:{
            _selectedIndex2 = anIndex;
            
            _lbCapacity.text = [NSString stringWithFormat:@"%@",[[arrayCapacity objectAtIndex:anIndex] objectForKey:@"boxCaptcityDesc"]];
            capacityId= [[[arrayCapacity objectAtIndex:anIndex] objectForKey:@"boxCapacityID"] intValue];
            break;}
        default:
            break;
    }
    [self getSearchResult];
}
- (void)leveyPopListViewDidCancel
{
    //edtCity.text = @"You have cancelled";
}
 */
@end
